import { defineStore } from "pinia";

export const useIndexDB = defineStore("indexDB", {
  state: (): {
    db: IDBDatabase | null;
  } => ({
    db: null,
  }),
  actions: {
    // 添加或新增数据
    async addOrUpdateMsg(key: string, msg: any) {
      const objectStore = this.db
        ?.transaction("message", "readwrite")
        .objectStore("message") as IDBObjectStore;
      const data = objectStore.get(key);
      data.onsuccess = (res: any) => {
        if (res.target.result) {
          // 数据存在，修改
          objectStore.put(msg);
        } else {
          // 数据不存在，新增一条
          objectStore.add(msg);
        }
      };
    },
  },
  getters: {
    // 初始化本地数据库
    initDB(): Function {
      const state = this;
      return async (): Promise<boolean> =>
        new Promise((resolve, reject) => {
          // 打开数据库
          const request = indexedDB.open("chatDB", 1);
          request.onerror = (e: any) => {
            console.error("数据库连接失败", e);
            reject(false);
          };
          request.onsuccess = (e: any) => {
            console.warn("数据库连接成功", e);
            state.db = e.target.result;
            resolve(true);
          };
          request.onupgradeneeded = (e: any) => {
            // 判断表存不存在
            const db = e.target.result;
            if (!db.objectStoreNames.contains("message")) {
              // 如果表不存在，则新增表
              db.createObjectStore("message", { keyPath: "key" });
            }
          };
        });
    },

    // 读取数据
    // 读取数据
    getData(state): Function {
      return async (key: string): Promise<any> =>
        new Promise((resolve, reject) => {
          const objectStore = state.db
            ?.transaction("message", "readonly")
            .objectStore("message") as IDBObjectStore;
          const data = objectStore.get(key);
          data.onsuccess = () => resolve(data.result);
          data.onerror = () => reject([]);
        });
    },
  },
});
